<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('公司全称')" prop="companyName">
            <el-autocomplete
              v-if="!form.id"
              v-model="form.companyName"
              class="inline-input name"
              :fetch-suggestions="companyQuerySearch"
              :placeholder="$t('公司全称')"
              :trigger-on-focus="false"
              :maxlength="100"
              @select="companyHandleSelect"
            >
              <template v-if="enableTyc" slot="append">
                <a @click="companyHandleSelect">{{ $t('查询工商信息') }}</a>
              </template>
            </el-autocomplete>
            <el-input v-else v-model="form.companyName" readonly show-word-limit maxlength="100">
              <template v-if="enableTyc" slot="append">
                <a @click="companyHandleSelect">{{ $t('查询工商信息') }}</a>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('公司简称')" prop="companyShortName">
            <el-input v-model="form.companyShortName" :placeholder="$t('公司简称')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('企业统一社会信用代码')" prop="creditCode">
            <el-input v-model="form.creditCode" :placeholder="$t('企业统一社会信用代码')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('法人代表')" prop="legalPerson">
            <el-input v-model="form.legalPerson" :placeholder="$t('法人代表')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <!--行业-->
        <Industry ref="industryZj" :buss-data="form" />
        <el-col :span="12">
          <el-form-item :label="$t('注册地-国家')" prop="country">
            <el-select v-model="form.country" :clearable="true" :placeholder="$t('注册地-国家')" filterable @change="updateCountry">
              <el-option
                v-for="area in countryOptions"
                :key="area.id"
                :label="$t(area.name)"
                :value="area.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--地域-->
        <Area v-if="form.country === '1'" ref="cityZj" :buss-data="form" />
        <el-col :span="12">
          <el-form-item :label="$t('注册详细地址')" prop="detailsRegistered">
            <el-input v-model="form.detailsRegistered" :placeholder="$t('注册详细地址')" show-word-limit maxlength="500" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('成立时间')" prop="setDate">
            <DatePicker v-model="form.setDate" :placeholder="$t('成立时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('注册资本') + $t('金额单位')" prop="capitalRegistered">
            <Money v-model="form.capitalRegistered" unit="w" :placeholder="$t('注册资本') + $t('金额单位')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('注册资本币种')">
            <el-select v-model="form.currency" clearable filterable :placeholder="$t('注册资本币种')">
              <el-option
                v-for="dict in currencyOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('实收资本') + $t('金额单位')" prop="actualCapital">
            <Money v-model="form.actualCapital" unit="w" :placeholder="$t('实收资本') + $t('金额单位')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('实收资本币种')">
            <el-select v-model="form.actualCurrency" clearable filterable :placeholder="$t('实收资本币种')">
              <el-option
                v-for="dict in actualCurrencyOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('上市情况')" prop="listingSituation">
            <dict-select
              v-model="form.listedSituation"
              dictionary="bf_group_listed_situation"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('上市板块')" prop="listedSector">
            <dict-select
              v-model="form.listedSector"
              dictionary="bf_group_listed_sector"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('股票代码')" prop="stockCode">
            <el-input v-model="form.stockCode" :placeholder="$t('股票代码')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('目前员工人数')" prop="upStaffNumber">
            <el-input v-model="form.upStaffNumber" :placeholder="$t('目前员工人数')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col v-if="isShowGroupAddBtn" :span="12">
          <el-form-item :label="$t('所属组')" prop="createBy.groups" @mouseover.native="showDeleteBtn = true" @mouseleave.native="showDeleteBtn = false">
            <div style="display: flex;">
              <el-select v-model="form.groups" filterable multiple clearable>
                <el-option
                  v-for="dict in groupOptions"
                  :key="dict.id"
                  :label="$t(dict.name)"
                  :value="dict.id"
                >
                  <span style="float: left">{{ $t(dict.name) }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ $t(dict.typeName) }}</span>
                </el-option>
              </el-select>
              <div class="addGLR">
                <div v-if="form.groups && showDeleteBtn" @click="form.groups = undefined"><i class="el-icon-circle-close" style="color: #c5c5c5;width: 25px;" /></div>
                <div class="addGLRText" @click="addGroup">{{ $t('添加组') }}</div>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('创建人')" prop="createBy.nickName">
            <el-input v-model="form.createBy.nickName" disabled show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('更新时间')" prop="updateTime">
            <el-input v-model="form.updateTime" disabled show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('经营范围')" prop="businessScope">
            <el-input v-model="form.businessScope" type="textarea" :placeholder="$t('经营范围')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('企业简介')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('企业简介')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <SaveBtn has-permi="company:base" :cancel-show="openLocation !== 'companyHome'" />
    </div>
    <el-dialog v-el-drag-dialog :visible.sync="groupOpen" :title="$t('添加组')" :close-on-click-modal="false" :lock-scroll="false" width="500px" append-to-body>
      <companyBaseGroup ref="companyBaseGroup" @groupHandle="groupHandle" />
    </el-dialog>
  </div>
</template>

<script>
    import { saveCompanyBase, getCompanyBase, companyDetailsByName, companyListByName } from '@/api/company/base/companyBase'
    import { getUserProfile } from '@/api/system/user'
    // 行业组件
    import Industry from '@/components/Industry'
    // 省市组件
    import Area from '@/components/Area'
    import companyBaseGroup from '@/views/company/group/companyBaseGroupForm.vue'
    import { checkOpenBtnStatus, listCompanyBaseGroup } from '@/api/company/group/companyBaseGroup'
    import { getCountryList } from '@/api/system/area/sysArea'
    // import { moneyFormat } from '@/utils/ruoyi'
    export default {
        components: {
          Industry,
          companyBaseGroup,
          Area
        },
        data() {
          const numberAstrict = (rule, value, callback) => {
            if (value !== undefined && value !== '' && value !== null) {
              if (rule.field === 'upStaffNumber') {
                var regNumber = /^[0-9]*[0-9][0-9]*$/
                if (!regNumber.test(value)) {
                  callback(new Error(this.$t('只能录入正整数')))
                }
                if (value.length > 10 || value > 2147483647) {
                  callback(new Error(this.$t('数量过大')))
                }
              }
            }
            callback()
          }
            return {
                // 注册资本币种字典
                currencyOptions: [],
                // 是否上市
                yesOrNoOptions: [],
                // 国家区域列表
                countryOptions: [],
                // 实收资本币种字典
                actualCurrencyOptions: [],
                // 表单参数
                form: {
                  createBy: {
                    id: undefined,
                    nickName: undefined
                  }
                },
                // 遮罩层
                loading: false,
                // 打开页面的位置，如果是通过项目home页面的路由打开，保存时不调用刷新list页面的方法
                openLocation: undefined,
                // 表单校验
                rules: {
                  companyName: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  companyShortName: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  industryFirst: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  industrySecond: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  provinceRegistered: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  cityRegistered: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
                  upStaffNumber: [{ validator: numberAstrict, trigger: 'blur' }]
                },
                // 天眼查查询条件
                tycParam: {
                  id: '',
                  companyName: '',
                  tycId: ''
                },
                orgTypeCompany: '',
                enableTyc: undefined,
                groupOptions: [],
                groupOpen: false,
                showDeleteBtn: false,
                isShowGroupAddBtn: false
            }
        },
        mounted() {
            this.$bus.$emit('async_done')
            this.enableTyc = (window.localStorage.getItem('enableTyc') === 'true')
            // 加载所属组
            this.groupOptions = []
            listCompanyBaseGroup({}).then(response => {
              this.groupOptions = response.rows
            })
        },
        created() {
            this.getDicts('currency').then(response => {
                this.currencyOptions = response.data
                this.actualCurrencyOptions = response.data
            })
            this.getDicts('sys_yes_no').then(response => {
              this.yesOrNoOptions = response.data
            })
          // 获取是否显示 添加组按钮
          checkOpenBtnStatus().then(response => {
            this.isShowGroupAddBtn = response.data
          })
          // 获取所有的省集合
          getCountryList().then(response => {
            this.countryOptions = response.data
          })
        },
        methods: {
          // 初始化数据
          async init(rowId) {
            if (rowId) {
              if (rowId.companyId) {
                rowId = rowId.companyId
              } else {
                rowId = rowId.id
              }
            }
            this.loading = true
            if (rowId != null && rowId !== undefined) {
              getCompanyBase(rowId).then(response => {
                this.form = response.data
                if (!this.form.createBy) {
                  this.form.createBy = { nickName: '' }
                }
                this.loading = false
                this.$nextTick(() => {
                  this.$refs.industryZj.initIndustrySecond()
                  this.$refs.cityZj.initCity()
                  this.$refs.cityZj.initDistrict()
                })
                this.loading = false
              })
            } else {
              this.reset()
              getUserProfile().then(response => {
                this.form.createBy.id = response.data.id
                this.form.createBy.nickName = response.data.nickName
                this.loading = false
              })
            }
          },
          // 修改国家删除下面的省份、市、区
          updateCountry() {
            this.form.provinceRegistered = undefined
            this.form.cityRegistered = undefined
            this.form.districtRegistered = undefined
          },
          // 表单重置
          reset() {
            this.form = {
              companyShortName: undefined,
              creditCode: undefined,
              legalPerson: undefined,
              country: undefined,
              setDate: undefined,
              industryFirst: undefined,
              industrySecond: undefined,
              provinceRegistered: undefined,
              districtRegistered: undefined,
              cityRegistered: undefined,
              detailsRegistered: undefined,
              capitalRegistered: undefined,
              currency: undefined,
              businessScope: undefined,
              actualCapital: undefined,
              actualCurrency: undefined,
              stockCode: undefined,
              listingAddress: undefined,
              market: undefined,
              logoInfo: undefined,
              tycId: undefined,
              groups: undefined,
              createBy: {
                id: undefined,
                nickName: undefined
              }
            }
            this.resetForm('form')
          },
          // 取消按钮
          cancel() {
            if (this.openLocation) {
              if (this.$parent.$parent.$parent?.formOpen !== undefined) {
                this.$parent.$parent.$parent.formOpen = false
                this.$parent.$parent.$parent.init()
              }
            } else {
              this.$parent.$parent.formOpen = false
            }
            this.reset()
          },
          /** 提交按钮 */
          submitForm: function() {
            this.$refs['form'].validate(valid => {
              if (valid) {
                this.loading = true
                this.form.orgType = this.orgTypeCompany
                saveCompanyBase(this.form).then(response => {
                  if (response.code === 200) {
                        this.msgSuccess(this.$t('保存成功'))
                        // 如果是通过项目home页面的路由打开，保存时不调用刷新list页面的方法
                        if (this.$parent.$parent.homeOpen) {
                          this.$parent.$parent.homeOpen = false
                        } else if (this.openLocation) {
                          // 项目里边保存
                          this.loading = false
                          if (this.$parent.$parent.$parent?.formOpen !== undefined) {
                            this.$parent.$parent.$parent.formOpen = false
                            this.$parent.$parent.$parent.init()
                          }
                        } else {
                          this.$parent.$parent.formOpen = false
                          this.$parent.$parent.getList()
                          this.reset()
                          this.loading = false
                        }
                  } else {
                    this.msgError(response.msg)
                  }
                  this.loading = false
                })
              } else {
                this.locationError(document)
              }
            })
          },
          // 标的公司查询
          companyQuerySearch(queryString, cb) {
            companyListByName(queryString).then(res => {
              if (res.code === 200) {
                cb(res.data)
              }
            })
          },
          formCleaing() {
            this.form.companyShortName = ''
            this.form.creditCode = ''
            this.form.legalPerson = ''
            this.form.setDate = ''
            this.form.industryFirst = ''
            this.form.industrySecond = ''
            this.form.provinceRegistered = ''
            this.form.cityRegistered = ''
            this.form.detailsRegistered = ''
            this.form.capitalRegistered = ''
            this.form.businessScope = ''
            this.form.currency = ''
            this.form.tycId = ''
            this.form.logoInfo = ''
          },
          // 快速添加组
          addGroup() {
            this.groupOpen = true
            this.$nextTick(() => {
              this.$refs.companyBaseGroup.init()
            })
          },
          groupHandle(data) {
            this.groupOptions.push(data)
          },
          // 标的公司选择后事件
          companyHandleSelect(item) {
            var companyName = this.form.companyName
            if (companyName === '' || companyName === undefined) {
              this.msgError(this.$t(this.$t('请先输入公司全称！')))
              return
            }
            this.tycParam.id = this.form.id
            // this.tycParam.tycId = item.id || this.form.tycId
            this.tycParam.companyName = companyName
            this.tycParam.orgType = item.type === 'click' ? '1' : item.type
            this.orgTypeCompany = item.type
            companyDetailsByName(this.tycParam).then(res => {
              if (res.msg === 'exist') {
                this.form.companyName = ''
                this.msgError(this.$t('公司已存在,请重新录入！'))
              } else if (res.msg === 'nofind') {
                this.form.companyName = ''
                this.msgError(this.$t('天眼查没有获取到该公司信息！'))
              } else {
                this.formCleaing()
                // 公司简称
                this.form.companyShortName = res.data.companyShortName
                // 公司名称
                this.form.companyName = res.data.companyName
                // 企业统一社会信用代码
                this.form.creditCode = res.data.creditCode
                // 法人代表
                this.form.legalPerson = res.data.legalPerson
                // 成立时间
                this.form.setDate = res.data.setDate
                // 一级行业
                this.form.industryFirst = res.data.industryFirst
                this.form.industrySecond = res.data.industrySecond
                this.$refs.industryZj.initIndustrySecond()
                // 注册地-省
                this.form.provinceRegistered = res.data.provinceRegistered
                // 注册市
                this.form.cityRegistered = res.data.cityRegistered
                this.$refs.cityZj.initCity()
                this.$refs.cityZj.initDistrict()
                 // 注册区
                this.form.districtRegistered = res.data.registerDistrict
                // 注册地-详细地址
                this.form.detailsRegistered = res.data.detailsRegistered
                // 注册资本金额
                this.form.capitalRegistered = res.data.capitalRegistered
                // 注册资本币种
                this.form.currency = res.data.currency
                // 经营范围
                this.form.businessScope = res.data.businessScope
                // 天眼查ID
                this.form.tycId = res.data.tycId
                // 公司logo
                this.form.logoInfo = res.data.logoInfo
                // 企业简介
                this.form.remark = res.data.remark
                // 实收资本
                this.form.actualCapital = res.data.actualCapital
                // 实收资本币种
                 this.form.actualCurrency = res.data.actualCurrency
                 this.$forceUpdate()
                this.msgSuccess(this.$t('已获取工商信息！'))
              }
            })
          }
        }
    }
</script>

<style lang="scss" scoped>
  .tianyan{
    border: 1px solid #DCDFE6;
    width: 17%;
    border-radius: 5px;
    height: 36px;
    float: right;
    text-align: right;
    padding-right: 15px;
    border-left: 0px;
    color: #1E9FFF;
    margin-top: -37px;
    font-size: 13px;
  }

  .addGLR {
    height: 36px;
    position: absolute;
    right: 30px;
    z-index: 1 !important;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
    color: #9e9898;
    cursor: pointer;
    display: flex;
  }

  .addGLRText {
    padding: 0 10px;
    cursor: pointer;
    color: inherit;
    text-decoration: none;
    font-size: 14px;
    font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
    background-color: #f5f7fa;
    border: 1px solid #dcdfe6;
  }
</style>
